package cn.ulc.socket.admin.service.notice.impl;

import cn.hutool.core.convert.Convert;
import cn.ulc.common.constant.enums.AvailableStatus;
import cn.ulc.common.constant.enums.DeletedStatus;
import cn.ulc.common.exception.PlatformException;
import cn.ulc.common.model.param.PaginationParam;
import cn.ulc.socket.admin.common.BaseService;
import cn.ulc.socket.admin.model.dto.NoticeListDTO;
import cn.ulc.socket.admin.model.param.NoticeParam;
import cn.ulc.socket.admin.service.notice.NoticeServ;
import cn.ulc.store.dao.NoticeDao;
import cn.ulc.store.entity.Notice;
import cn.ulc.store.entity.staff.Staff;
import lombok.AllArgsConstructor;
import org.beetl.sql.core.engine.PageQuery;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
@AllArgsConstructor
public class NoticeServImpl extends BaseService implements NoticeServ {
  NoticeDao noticeDao;
  @Override
  public NoticeListDTO findListPage(String startDate, String endDate, PaginationParam pager) {
    Staff loginUser = getCurrentUser();
    Map<String,Object> condition = new HashMap<>();
    condition.put("startDate",startDate);
    condition.put("endDate",endDate);
    condition.put("companyId",loginUser.getCompanyId());
    PageQuery pageQuery = initPageQuery(pager);
    pageQuery.setParas(condition);
    noticeDao.findListPage(pageQuery);
    return new NoticeListDTO(pageQuery.getList(),pageQuery.getTotalRow());
  }

  @Override
  public Boolean changeStatus(Long id, AvailableStatus status) {
    long nid = Convert.toLong(id,0l);
    Notice entity = noticeDao.findOne(nid);
    if(entity == null) throw new PlatformException("未获取到公告信息");
    setBaseInfo(entity);
    entity.setStatus(status);
    noticeDao.save(entity);
    return true;
  }

  @Override
  public Boolean deleted(Long id) {
    long nid = Convert.toLong(id,0l);
    Notice entity = noticeDao.findOne(nid);
    if(entity != null) {
      setBaseInfo(entity);
      entity.setDeleted(DeletedStatus.DELETED);
      noticeDao.save(entity);
    }
    return true;
  }

  @Override
  public Long save(NoticeParam param) {
    boolean isEdit = param.getId() != null && param.getId() > 0;
    Notice entity = new Notice();
    if(isEdit){
      entity = noticeDao.findOne(param.getId());
      if(entity == null) throw new PlatformException("未获取到公告信息");
    }
    setBaseInfo(entity);
    entity.setStatus(AvailableStatus.AVAILABLE);
    entity.setContent(param.getContent());
    entity.setLocation(param.getLocation());

    noticeDao.save(entity);
    return entity.getId();
  }
}
